package top.infopub.mgr.util;


import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import top.infopub.exception.ServiceException;
import top.infopub.util.JsonUtils;


/**
 * 流工具
 * @author Awoke
 * @version 2018年10月15日
 * @see StreamRenderUtil
 * @since
 */
public class StreamRenderUtil {

    /**
     * @param obj  对象
     * @param response  
     * @param ContentType 规则 默认为  application/json;charset=UTF-8
     */
    public static void render(Object obj, HttpServletResponse response, String ContentType) {
        PrintWriter out = null;
        try {
            if (null == ContentType) {
                ContentType = "application/json; charset=UTF-8";
            }
            response.setContentType(ContentType);
            response.setHeader("Pragma", "No-Cache");
            response.setHeader("Cache-Control", "No-Cache");
            response.setDateHeader("Expires", 0);
            out = response.getWriter();
            String result = JsonUtils.toString(obj);
            out.write(result);
            out.flush();
        }
        catch (Exception e) {
            e.printStackTrace();
            // 给异常拦截器统一处理
            throw new ServiceException("StreamRender失败");
        }
        finally {
            IOUtils.closeQuietly(out);
        }
    }

}
